package dome1.network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

//客户端
public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;

    public UdpEchoClient(String serverIp, int serverPort) throws SocketException {
        socket = new DatagramSocket();
        //IP和端口号要记录
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }
    public void start() throws IOException {
        System.out.println("客户端启动！");
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("请输入要发送的请求");

            //1、从控制台读取用户输入（String）
            String request = scanner.next();

            //2、构造请求并发送
            //在构造请求数据报的时候，不光要有数据，还得有目标

            //(构造请求）
            // 将用户输入转为字节，长度为从0到字节数，将IP地址转为JAVA能识别的InetAddress对象并保存, 保存端口号
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), 0, request.getBytes().length,
                    InetAddress.getByName(serverIp), serverPort);
            //(发送)
            socket.send(requestPacket);

            //6、读取响应数据
            //先创建长度为4096的空字节数组，并另数据报的长度为4096；
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            //将得到的响应数据读取
            socket.receive(responsePacket);

            //7、显示响应到控制台上

            //获取读取到的数据，转为String并保存
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            //显示在控制台上
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1",9090);
        udpEchoClient.start();
    }
}
